import { defineStore } from 'pinia'
import { request, baseAdminAPI } from '@/service/request'
import Storage from '@/utils/Storage'
import { TOKEN_KEY } from '@/config/constant'
import { genMenuList } from '@/utils/routerUtils'

export interface UserInfoProps {
  username?: string
  _id?: string
  nickName?: string
}

export interface UserProps {
  isLogin: boolean
  token?: string
  userInfo: UserInfoProps
  menuList: any[]
}

export const useUserStore = defineStore('user', {
  state: (): UserProps => ({
    isLogin: false,
    userInfo: {},
    token: Storage.getStorage(TOKEN_KEY),
    menuList: []
  }),

  getters: {
    hasUserInfo: state => JSON.stringify(state.userInfo) !== '{}'
  },

  actions: {
    async loginAndFetch(payload: any) {
      await this.login(payload)
      return await this.fetchCurrentUser()
    },

    async login(payload: any) {
      const rawData = await request<{ token: string }>(`${baseAdminAPI}/admin/login`, 'post', payload, 'login')
      this.token = rawData.data.token
      Storage.setStorage(TOKEN_KEY, this.token)
    },

    async fetchCurrentUser() {
      const rawData = await request<UserInfoProps>(`${baseAdminAPI}/admin/getUserInfo`, 'get')
      this.updateUser(rawData.data)
      return rawData.data
    },

    updateUser(data: UserInfoProps) {
      this.isLogin = true
      this.userInfo = { ...data }
      this.menuList = genMenuList()
      // console.log(this.menuList)
    },

    logout() {
      this.token = ''
      this.isLogin = false
      Storage.remove(TOKEN_KEY)
      delete axios.defaults.headers.common['Authorization']
      location.reload() // 为了重新实例化vue-router对象 避免bug
    }
  }
})
